package com.spyx.user.controller;


import com.alibaba.fastjson.JSONObject;
import com.atyx.spyx.enums.UserType;
import com.atyx.spyx.model.user.User;
import com.atyx.spyx.vo.user.LeaderAddressVo;
import com.atyx.spyx.vo.user.UserLoginVo;
import com.spyx.auth.AuthContextHolder;
import com.spyx.common.JwtHelper;
import com.spyx.constant.RedisConst;
import com.spyx.exception.SpyxException;
import com.spyx.result.Result;
import com.spyx.result.ResultCodeEnum;
import com.spyx.user.service.UserService;
import com.spyx.user.utils.ConstantPropertiesUtil;
import com.spyx.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "微信登录")
@CrossOrigin
@RequestMapping("api/user/weixin")
public class WebApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //更新用户数据  api/user/weixin/auth/updateUser
    @PostMapping("auth/updateUser")
    @ApiOperation("更新用户信息")
    public Result updateuser(@RequestBody User u){
        //先根据id查询用户信息
        Long userId = AuthContextHolder.getUserId();
        User user1 = userService.getById(userId);
        user1.setSex(u.getSex());
        user1.setPhotoUrl(u.getPhotoUrl());
        user1.setNickName(u.getNickName());
        //更新用户信息信心
        userService.updateById(user1);
        return Result.ok();
    }




    //完整：  api/user/weixin/wxLogin/{code}
    @GetMapping("wxLogin/{code}")
    public Result loginWx(@PathVariable("code")String  code) throws Exception {
     //1.先获取code(临时票据)
        System.out.println("code="+code);
        if(StringUtils.isEmpty(code)){
            throw new SpyxException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
    //2.绑定需要发送的appid和密钥等数据
        StringBuffer url = new StringBuffer();
             url.append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl= String.format(url.toString(), ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET, code);
       //3.发送请求到腾讯服务器,result中存储了服务器返回的session_key和openId
        String result = HttpClientUtils.get(accessTokenUrl);

       //4.从result中获取返回的session_key和openid,需要先转换成JSON格式
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(!StringUtils.isEmpty(jsonObject.getString("errorcode"))){
            throw new SpyxException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        //5.先根据openid查询数据库,判断是否有数据,有数据表示已经登录过，没有数据，表示未登录过，将登录用户的openid存储到mysql中
        //5.1 根据openid查询数据库
        User user = userService.getUserByOpenId(openid);
        //5.2 判断用户
        if(user==null){
            user = new User();
            user.setUserType(UserType.USER);
            user.setPhotoUrl("");
            user.setNickName(openid);//暂时使用openid作为昵称
            user.setOpenId(openid);
            user.setIsNew(0); //0表示新用户
            userService.save(user);
        }
       //6.如果用户已经登录过，根据用户id,查询该用户的提货点和团长的信息
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());
        //7. 在redis中存储登录的用户信息
        //7.1 查询登录用户的完整信息,根据用户id,查询用户数据
        UserLoginVo userLoginVo=userService.getUserLoginVo(user.getId());
        //7.2 存储到redis中 key=user:login:userid
        redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(),userLoginVo,
                RedisConst.USERKEY_TIMEOUT, TimeUnit.HOURS);

        //8.返回最终结果给前端
        Map map=new HashMap<>();
        map.put("user",user);
        map.put("leaderAddressVo",leaderAddressVo);
        //存储token
        String token = JwtHelper.createToken(user.getId(), user.getNickName());
        map.put("token",token);

        return Result.ok(map);
    }
}
